//
//  SYComposeViewController.swift
//  YANAWeibo
//
//  Created by mac on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class SYComposeViewController: UIViewController, UITextViewDelegate {
    
    /// 懒加载自定义btn
    private lazy var rightButton: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        btn.setTitle("发送", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        //设置文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        btn.frame.size = CGSize(width: 45, height: 30)
        return btn
    }()
    
    /// 懒加载 自定义label
    private lazy var titleView: UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 17)
        
        if let name = SYUserAccountViewModel.sharedUserAccount.userAccount?.name {
            let title: String = "发微博\n\(name)"
            // 获取name在文本中的range
            let range = (title as NSString).rangeOfString(name)
            // 创建富文本对象
            let attributteStr = NSMutableAttributedString(string: title)
            // 设置文本的颜色
            attributteStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
            // 设置文本字体大小
            attributteStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(13), range: range)
            
            label.attributedText = attributteStr
            
        } else {
            label.text = "发微博"
        }
        label.numberOfLines = 0
        label.sizeToFit()
        label.textAlignment = .Center
        return label
    }()
    
    /// 懒加载 自定义textview
    private lazy var textView: SYComposeTextView = {
        let view = SYComposeTextView()
        view.alwaysBounceVertical = true
        view.font = UIFont.systemFontOfSize(30)
        view.delegate = self
        view.placeHolder = "请告诉你现在的心情😈"
        return view
    }()
    
    private lazy var toolBar: SYComposeToolBar = {
        let view = SYComposeToolBar(frame: CGRectZero)
        return view
    }()
    
    /// 懒加载自定义配图
    private lazy var pictureView: SYComposePictureView = {
        let view = SYComposePictureView()
        view.backgroundColor = self.view.backgroundColor
        return view
    }()
    
    /// 懒加载表情键盘
    private lazy var emoticonKeyboard: SYEmoticonKeyBoard = {
        let view = SYEmoticonKeyBoard()
        // 设置大小
        view.size = CGSize(width: self.textView.width, height: 216)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        // 监听键盘改变通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 监听表情按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedEmoticon:", name: DidSeletedEmoticonNotification, object: nil)
        
        // 监听删除表情按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedDeleteEmoticon", name: DidSeletedDeleteEmotiocnButtonNotification, object: nil)
    }
    
    @objc private func didSelectedEmoticon(noti: NSNotification) {
        guard let emoticon = noti.object as? SYEmoticon else {
            return
        }
        textView.insertEmoticon(emoticon, font: textView.font!)
        
        
    }
    
    private func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        setupNavUI()
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        // 设置约束u
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
        // toolbar 的监听回调
        toolBar.didSeletedButtonClosure = { [weak self] (type: SYComposeToolBarButtonType) in
            switch type {
            case .Picture:
                self?.didSelectedPicture()
            case .Mention:
                print("mention")
            case .Trend:
                print("trend")
            case .Emoticon:
                self?.didSelectesEmojicon()
            case .Add:
                print("add")
            }
            print(self)
        }
        
        // 点击图片按钮的回调
        pictureView.didSelectedAddImageClosure = { [weak self] in
            self?.didSelectedPicture()
        }
        
    }
    
    // 监听键盘 滚动通知
    @objc private func keyboardChangeFrame(noti: NSNotification) {
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey]! as! NSValue).CGRectValue()
        let animationDuration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey]! as! NSNumber).doubleValue
        
        // 更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - view.height)
        }
        
        // 动画
        UIView.animateWithDuration(animationDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }

    /**
     设置导航栏视图
     */
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancleBtnClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        // 初始化右侧按钮禁用
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
    }
    
    @objc private func cancleBtnClick() {
        view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendAction() {
       
        
        if pictureView.images.count > 0 {
            // 发送微博配图
            uploadSendPic()
        } else {
            // 发送文字
            updateSendText()
        }
    }
    
    // 发送微博配图
    private func updateSendText() {
        // 准备参数
        let accesstoken = SYUserAccountViewModel.sharedUserAccount.accessToken!
        let status = textView.emoticonText
        SVProgressHUD.show()
        // 发送文字
        SYNetWorkTools.sharedTools.update(accesstoken, status: status) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("糟糕网破了😈")
                return
            }
            SVProgressHUD.showSuccessWithStatus("微博已发射成功😜")
            self.cancleBtnClick()
        }
        
    }
    // 发送文字
    private func uploadSendPic() {
        let accesstoken = SYUserAccountViewModel.sharedUserAccount.accessToken!
        let status = textView.emoticonText
        SVProgressHUD.show()
        let image = pictureView.images.first!
        SYNetWorkTools.sharedTools.upload(accesstoken, status: status, image: image, callBack: { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("糟糕网破了😈")
                return
            }
            SVProgressHUD.showSuccessWithStatus("微博已发射成功😜")
            self.cancleBtnClick()
        })
    
    }
    
     // MARK: -- UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.view.endEditing(true)
    }
    
    deinit {
        // 移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

extension SYComposeViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    /**
     点击图片操作
     */
    func didSelectedPicture() {
        let pictureVC = UIImagePickerController()
        pictureVC.delegate = self
        // 是否支持该类型
//        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
//            pictureVC.sourceType = .Camera
//        } else {
//            pictureVC.sourceType = .PhotoLibrary
//        }
        
        pictureVC.sourceType = .PhotoLibrary
        
        // 判断摄像头是否可用
//        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
//            print("前置摄像头可用")
//        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
//            print("后置摄像头可用")
//        } else {
//            print("都不可用")
//        }
        
        presentViewController(pictureVC, animated: true, completion: nil)
        
    }
    
    /**
     点击表情图片的操作
     */
    @objc private func didSelectesEmojicon() {
        if textView.inputView == nil {
            textView.inputView = emoticonKeyboard
            toolBar.showEmoticonIcon(true)
        } else {
            textView.inputView = nil
            toolBar.showEmoticonIcon(false)
        }
        // 成为第一响应者
        textView.becomeFirstResponder()
        // 重新加载自定义的inputview
        textView.reloadInputViews()
    }
    
    @objc private func didSelectedDeleteEmoticon() {
        // 删除textview内容
        textView.deleteBackward()
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        let width = image.size.width
        let scaleImage = image.scaleImageWithWidth(width)
        pictureView.addImage(scaleImage)
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}
